package sliding_window;

public class minSubArrayLen {
    public int minSubArrayLen2(int target, int[] nums) {
        int n = nums.length, sum = 0,len = Integer.MAX_VALUE;
        for (int left = 0, right = 0; right < n; right++) {
            sum += nums[right]; // 进窗⼝
            while (sum >= target) // 判断
            {
                len = Math.min(len, right - left + 1); // 更新结果
                sum -= nums[left++]; // 出窗⼝
            }
        }
        return len == Integer.MAX_VALUE ? 0 : len;
    }
    public int minSubArrayLen(int target, int[] nums) {
        int n = nums.length;
        int len = 0;
        int left = 0;
        int right = 0;

        int total = 0;
        int min = Integer.MAX_VALUE;

        while (right <= n && left < n) {

            if (total >= target) {
                if (min > len) {
                    min = len;
                }
                total -= nums[left];
                --len;
                ++left;
            } else {
                ++len;
                if(right < n){
                    total += nums[right];

                }
                right++;
            }
        }
        return min == Integer.MAX_VALUE ? 0 : min;
    }
}
